package com.amkai.aes.webservice.binary.objecthandler.casehistory;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amkai.aes.generatedbeans.cdmcasehistory.CdmCaseHistory;
import com.amkai.aes.generatedbeans.cdmcasehistory.ReadyToBillHistoryEntry;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

/**
 * #14695
 * @author lkovari
 *
 */
public class ReadyToBillStatusHistoryDataManager {
	private static final Log log = LogFactory.getLog(ReadyToBillStatusHistoryDataManager.class);

	/**
	 * #14695
	 * @param sm
	 * @param readyToBillHistoryEntry
	 * @throws Exception
	 */
	public static void storeReadyToBillStatusEntry(SessionManager sm, ReadyToBillHistoryEntry readyToBillHistoryEntry) throws Exception {
		try {
			sm.openTransaction();
			sm.saveRAD(readyToBillHistoryEntry);
//FIXME save Case history			
			sm.commitTransaction();
		}
		catch (Exception e) {
			sm.rollbackTransaction();
			e.printStackTrace();
			log.error("StoreReadyToBillStatusEntry", e);
			throw e;
		}
	}
	
	/**
	 * #14695
	 * @param sm
	 * @param cdmCaseHistory
	 * @return
	 * @throws Exception
	 */
	public static List<ReadyToBillHistoryEntry> getReadyToBillStatusEntry(SessionManager sm, CdmCaseHistory cdmCaseHistory) throws Exception {
		List< ReadyToBillHistoryEntry> history = new ArrayList< ReadyToBillHistoryEntry>();
		try {
			String queryString = "SELECT rbsh " +
					             "FROM ReadyToBillHistoryEntry rbsh " +
					             "LEFT JOIN FETCH rbsh.changedBy who " +
					             "LEFT JOIN FETCH who.person per " +
					             "WHERE rbsh.cdmCaseHistory.id = :cchId ORDER BY rbsh.when DESC";
			history = sm.execute(queryString).setEntity("cchId", cdmCaseHistory).list();
		}
		catch (Exception e) {
			sm.rollbackTransaction();
			e.printStackTrace();
			log.error("GetReadyToBillStatusEntry", e);
			throw e;
		}
		return history;
	}
	
}
